package models

import (
	"time"

	log "github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

type SipAccount struct {
	Id         int
	Username   string `orm:"size(16);unique"`
	Password   string `orm:"size(16)"`
	UpdateTime time.Time
}

func RegSipAccount() {
	orm.RegisterModel(new(SipAccount))
}

func InsertNewAccount(user, pwd string) error {

	newAccount := &SipAccount{
		Username:   user,
		Password:   pwd,
		UpdateTime: time.Now(),
	}

	o := orm.NewOrm()
	o.Using("default")

	err := o.Read(newAccount, "Username")
	if err != nil {
		_, err = o.Insert(newAccount)
		log.Debug("insert user:%v,user:%v,pwd:%v", user, pwd)
	} else {
		newAccount.Password = pwd
		newAccount.UpdateTime = time.Now()
		_, err = o.Update(newAccount, "Password")
		log.Debug("update user password:%v,user:%v,pwd:%v", user, pwd)
	}

	return err
}

func GetAccountInfo(user string) (*SipAccount, error) {

	newAccount := &SipAccount{
		Username: user,
	}

	o := orm.NewOrm()
	o.Using("default")

	err := o.QueryTable(new(SipAccount)).Filter("Username", user).One(newAccount)
	if err != nil {
		return nil, err
	}

	return newAccount, nil
}

func DelAccount(user string) error {

	delAccount := &SipAccount{
		Username: user,
	}
	o := orm.NewOrm()
	o.Using("default")

	_, err := o.Delete(delAccount, "Username")

	return err
}

type IpccSipClient struct {
	PkClientUser string `orm:"size(64);pk"`
	RegServer    string
	ClientAddr   string
	UpDateTime   time.Time `orm:"auto_now;type(datetime)"`
}

func RegSipRegistor() {
	orm.RegisterModel(new(IpccSipClient))
}

func GetSipRegHost(user string) (string, int, error) {

	host := &IpccSipClient{}
	o := orm.NewOrm()
	o.Using("default")

	err := o.QueryTable(new(IpccSipClient)).Filter("PkClientUser", user).One(host)
	return host.RegServer, 5180, err
}

func RegSipClient(user, clientAddr, server string) error {

	newClient := &IpccSipClient{
		PkClientUser: user,
		RegServer:    server,
		ClientAddr:   clientAddr,
	}
	o := orm.NewOrm()
	o.Using("default")

	err := o.Read(newClient, "PkClientUser")
	if err != nil {
		_, err = o.Insert(newClient)
		log.Debug("insert user:%v,user:%v,server:%v,addr:%v", user, server, clientAddr)
	} else {
		newClient.PkClientUser = user
		newClient.RegServer = server
		newClient.ClientAddr = clientAddr
		_, err = o.Update(newClient)
		log.Debug("update user:%v,user:%v,server:%v,addr:%v", user, server, clientAddr)
	}

	return nil
}
